package com.concerneyes.mine.TabActivity;


import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.concerneyes.CEApp;
import com.concerneyes.R;
import com.concerneyes.mine.model.HeaderImgModel;
import com.google.gson.Gson;

import photopicker.PhotoPickerActivity;
import photopicker.SelectModel;
import photopicker.intent.PhotoPickerIntent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import common.AbsActivity;
import common.PreferUtil;
import http.JsonMap;
import http.UploadAsyncTask;
import http.Url;
import util.Document;
import util.ImageUtil;
import view.MyUniversalDialog;


/**
 * Depiction:弹出可缩放的图层
 * <p>
 * Modify:
 * <p>
 * Author: Kevin Lynn
 * <p>
 * Create Date：2016年2月28日 下午5:04:42
 * <p>
 *
 * @version 1.0
 * @since 1.0
 */
public class ScaleImageActivity extends AbsActivity implements OnClickListener {
    private final int REQUEST_CODE_CAMERA = 1000;
    private final int REQUEST_CODE_GALLERY = 1001;
    private final int REQUEST_CODE_CROP = 1002;
    private ImageView iv_header;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.scale_image_layout);
        String imgUrl = getIntent().getExtras().getString("imgUrl");
        setTitle(R.string.my_photo);
        getRightBtn().setVisibility(View.VISIBLE);
        getRightBtn().setImageResource(R.drawable.nav_ico_more);
        initView(imgUrl);
    }


    @Override
    public void onRightAction(View v) {
        super.onRightAction(v);
        int width = this.getWindowManager().getDefaultDisplay().getWidth();
        final MyUniversalDialog dialog = new MyUniversalDialog(this);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setLayout(LayoutInflater.from(this).inflate(R.layout.dialog_photo, null),
                MyUniversalDialog.DialogGravity.CENTERBOTTOM, -2, -1);
        TextView takePhoto = (TextView) dialog.findViewById(R.id.take_photo);
        TextView fromPhoto = (TextView) dialog.findViewById(R.id.from_photo);
        TextView cancel = (TextView) dialog.findViewById(R.id.cancel);

        takePhoto.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(getOriginalHeaderPath())));
                startActivityForResult(camera, REQUEST_CODE_CAMERA);
                dialog.dismiss();
            }
        });
        fromPhoto.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                PhotoPickerIntent intent = new PhotoPickerIntent(ScaleImageActivity.this);
                intent.setSelectModel(SelectModel.SINGLE);
                intent.setShowCarema(true);
                startActivityForResult(intent, REQUEST_CODE_GALLERY);
                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private String getOriginalHeaderPath() {
        String fileName = "ceapp.png";
        String filePath = new Document().getCache() + fileName;
        return filePath;
    }

    private String getCropHeaderPath() {
        String fileName = "ceapp_crop.png";
        String filePath = new Document().getCache() + fileName;
        return filePath;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CAMERA) {
            // 拍照成功
            Uri uri = Uri.fromFile(new File(getOriginalHeaderPath()));
            startPhotoZoom(uri);
        } else if (requestCode == REQUEST_CODE_GALLERY) {
            ArrayList<String> imagepath = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
            Uri uri = Uri.fromFile(new File(imagepath.get(0)));
            startPhotoZoom(uri);
        } else if (requestCode == REQUEST_CODE_CROP) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap bitmap = extras.getParcelable("data");
                String filePath = getCropHeaderPath();
                boolean isSaveSuccess = ImageUtil.saveBitmap2File(bitmap, filePath);
                if (isSaveSuccess) {
                    // 保存图像成功，开始上传头像
                    modifyHeader(filePath);
                }
            }
        }
    }

    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CODE_CROP);
    }

    private void initView(String data) {
        String imgUrl = data != null ? data.toString() : "";
        iv_header = (ImageView) findViewById(R.id.iv_header);
        iv_header.setOnClickListener(this);
        ImageUtil.glideloadImage(imgUrl, iv_header, R.drawable.default_header);
    }

    @Override
    public void onClick(View v) {
        finish();
    }

    public void modifyHeader(final String headerPath) {
        String headerApi = Url.BaseUrl + "/user/updatePortrait?uid=" + PreferUtil.getUserId();
        UploadAsyncTask upload = new UploadAsyncTask(headerPath, headerApi) {

            @Override
            protected void onPreExcute(String tag) {
            }

            @Override
            protected void onPostExcute(String tag, List<Result> results) {

                if (results == null || results.size() == 0) {
                    showToast(R.string.upload_fail);
                    return;
                }

                String reponse = results.get(0).message;
                Log.e(this.getClass().getSimpleName(),"reponse==>"+reponse);
                JsonMap map = JsonMap.parseJson(reponse);
                HeaderImgModel model = null;
                if (map != null && map.getInt("code") == 200) {
                    try {
                        model = new Gson().fromJson(reponse, HeaderImgModel.class);
                    } catch (Exception e) {

                    }
                }
                if (model != null) {
                    PreferUtil.saveHeaderImgUrl(model.getUrl());
                    finish();
                }

                File headerFile = new File(headerPath);
                if (headerFile != null && headerFile.exists()) {
                    headerFile.delete();
                }
            }
        };
        upload.excute("file");
    }
}
